package com.kob.backend.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.UserService;
import com.kob.backend.utils.Result;
import com.kob.backend.utils.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.kob.backend.utils.ValidatorUtil.checkEmail;
import static com.kob.backend.utils.ValidatorUtil.checkPhone;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<User> update(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User cntUser = loginUser.getUser();

        int userId = Integer.parseInt(data.get("id"));
        String username = data.get("username");
        String nickname = data.get("nickname");
        String description = data.get("description");
        String phone = data.get("phone");
        String email = data.get("email");

        // 验证用户ID是否一致
        if (!cntUser.getId().equals(userId)) {
            return Result.fail(ResultEnum.UNAUTHORIZED);
        }
        if (username == null) {
            return Result.fail(ResultEnum.USERNAME_EMPTY);
        }
        username = username.trim();
        if (username.length() == 0) {
            return Result.fail(ResultEnum.USERNAME_EMPTY);
        }
        if (username.length() > 100) {
            return Result.fail(ResultEnum.USERNAME_LENGTH);
        }

        if (nickname == null) {
            return Result.fail(ResultEnum.NICKNAME_EMPTY);
        }
        nickname = nickname.trim();
        if (nickname.length() == 0) {
            return Result.fail(ResultEnum.NICKNAME_EMPTY);
        }
        if (nickname.length() > 50) {
            return Result.fail(ResultEnum.NICKNAME_LENGTH);
        }
        if (description.length() > 500) {
            return Result.fail(ResultEnum.DESCRIPTION_LENGTH);
        }

        if (!checkPhone(phone)) {
            return Result.fail(ResultEnum.PHONE_FORMAT);
        }
        if (!checkEmail(email)) {
            return Result.fail(ResultEnum.EMAIL_FORMAT);
        }

        if (!cntUser.getPhone().equals(phone)) {
            return Result.fail(ResultEnum.PHONE_EXIST);
        }
        if (!cntUser.getEmail().equals(email)) {
            return Result.fail(ResultEnum.EMAIL_EXIST);
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).ne("id", cntUser.getId());
        if (userMapper.selectCount(queryWrapper) > 0) {
            return Result.fail(ResultEnum.USERNAME_EXIST);
        }

        // 更新用户信息
        cntUser.setUsername(username);
        cntUser.setNickname(nickname);
        cntUser.setDescription(description);
        cntUser.setPhone(phone);
        cntUser.setEmail(email);
        userMapper.updateById(cntUser);

        // 返回更新后的用户信息（隐藏密码）
        cntUser.setPassword(null);
        return Result.success(cntUser);
    }

    @Override
    public Result updatePassword(Map<String, String> data) {
        // 获取当前登录用户
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User currentUser = loginUser.getUser();

        int userId = Integer.parseInt(data.get("id"));
        String oldPassword = data.get("oldPassword");
        String newPassword = data.get("newPassword");
        String confirmedNewPassword = data.get("confirmedNewPassword");

        // 验证用户ID是否一致
        if (!currentUser.getId().equals(userId)) {
            return Result.fail(ResultEnum.UNAUTHORIZED);
        }
        // 验证输入的密码是否有效
        if (oldPassword == null || newPassword == null || confirmedNewPassword == null) {
            return Result.fail(ResultEnum.PASSWORD_EMPTY);
        }

        oldPassword = oldPassword.trim();
        newPassword = newPassword.trim();
        confirmedNewPassword = confirmedNewPassword.trim();
        // 验证旧密码是否正确
        if (!passwordEncoder.matches(oldPassword, currentUser.getPassword())) {
            return Result.fail(ResultEnum.PASSWORD_INCORRECT);
        }

        if (newPassword.length() == 0 || confirmedNewPassword.length() == 0) {
            return Result.fail(ResultEnum.PASSWORD_EMPTY);
        }
        if (newPassword.length() > 100 || confirmedNewPassword.length() > 100) {
            return Result.fail(ResultEnum.PASSWORD_LENGTH);
        }
        if (!newPassword.equals(confirmedNewPassword)) {
            return Result.fail(ResultEnum.PASSWORD_CONFIRM);
        }

        // 更新密码
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        currentUser.setPassword(encodedNewPassword);
        userMapper.updateById(currentUser);

        return Result.success();
    }

    @Override
    public Result updateScore(Map<String, String> data) {
        // 获取当前登录用户
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User currentUser = loginUser.getUser();

        int userId = Integer.parseInt(data.get("id"));
        // 验证用户ID是否一致
        if (!currentUser.getId().equals(userId)) {
            return Result.fail(ResultEnum.UNAUTHORIZED);
        }

        Integer newScore = Integer.parseInt(data.get("score"));
        if (newScore > currentUser.getScore()) {
            currentUser.setScore(newScore);
        }
        userMapper.updateById(currentUser);

        return Result.success();
    }
}
